import axios from 'axios';
import { BASE_URL } from './config';
import { MessageBox, Notification } from 'element-ui';

const onRequest = (req) => {
  return req;
};
const onRequestError = (err) => {
  return Promise.reject(err);
};

const onResponse = (res) => {
  return Promise.resolve(res);
};
const onResponseError = (err) => {
  if (!err.response) {
    // network error
    MessageBox({
      message: '请检查你的网络，点击确定刷新页面。',
      title: '未知错误',
      type: 'error',
    }).then(() => {
      window.location.reload();
    });
  } else if (err.response.status === 401) {
    const { request: { responseURL } } = err;
    if (responseURL.indexOf("token") === -1) {
      Notification.warning({
        title: '操作失败',
        message: '登录后才能做这些操作哦'
      })
    }else {
      const { data={message: '账号或密码错误'}} = err.response.data

      Notification.warning({
        title: '登录失败',
        message: data.message
      })
    }
  } else if (err.response.status === 403) {
    const { data={message: '账号或密码错误'}} = err.response.data

    Notification.error({
      title: '权限不足',
      message: data.message
    })
  } else if (err.response.status === 404) {
    window.location.href = '/404';
  } else if (err.response.status === 422) {
    const { error_msg = "参数错误 请稍后尝试"} = err.response.data
    Notification.warning({
      title: '操作失败',
      message: error_msg
    })
  } else if (err.response.status === 429) {
    Notification.warning({
      title: '操作失败',
      message: '操作的太快了 先休息会吧~'
    })
  } else if (err.response.status >= 500) {
    MessageBox({
      message: '服务器错误，请联系管理员。',
      title: '服务器错误',
      type: 'error',
    });
  }
  return Promise.reject(err);
};

export const createAxios = () => {
  const config = {
    baseURL: BASE_URL,
    timeout: 60000,
    withCredentials: true,
  };
  const http = axios.create(config);
  http.interceptors.request.use(onRequest, onRequestError);
  http.interceptors.response.use(onResponse, onResponseError);
  return http;
};

export const http = createAxios();
